package cn.jinjimi.app.main.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import cn.jinjimi.base.util.AndroidUtils;
import cn.jinjimi.base.util.StringUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.BundleKey;
import cn.jinjimi.app.controller.event.UploadProfileEvent;
import cn.jinjimi.app.custom.event.CustomerListChangeEvent;
import cn.jinjimi.app.entity.Company;
import cn.jinjimi.app.search.CompanySearchProxy;
import cn.jinjimi.app.search.CompanySearchRecord;
import cn.jinjimi.app.search.Record;
import cn.jinjimi.app.search.SearchResultListener;
import cn.jinjimi.app.main.activity.SetCompanyActivity;
import cn.jinjimi.app.main.adapter.CompanySearchAdapter;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.XListView.XListView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

/**
 * Created by Roy
 * Date: 15/12/4
 */
public class CompanySearchFragment extends BaseFragment implements View.OnClickListener,
        SearchResultListener, AdapterView.OnItemClickListener {
    public List<Company> mListCompany;
    private EditText edSearch;
    private TextView tvNoResult;
    private XListView mListView;
    private CompanySearchAdapter mAdapter;
    private CompanySearchProxy searchProxy;
    private int selectType;
    private Company mCompany;

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_company_search;
    }

    @Override
    protected void initial() {
        initView();
        initListener();
    }

    protected void initView() {
        selectType = getArguments().getInt(SetCompanyActivity.TYPE_KEY, 0);
        edSearch = (EditText) findView().findViewById(R.id.edit_search);
        tvNoResult = (TextView) findView().findViewById(R.id.tv_noresult);
        mListView = (XListView) findView().findViewById(R.id.listview);
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(false);
        mListView.setTransparentBg();
        mAdapter = new CompanySearchAdapter(getActivity());
        mListView.setAdapter(mAdapter);

        searchProxy = new CompanySearchProxy(this, mListCompany);
    }

    protected void initListener() {
        mListView.setOnItemClickListener(this);
        findView().findViewById(R.id.tv_cancle).setOnClickListener(this);
        edSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                searchProxy.query(s.toString());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancle:
                getActivity().getSupportFragmentManager().popBackStack();
                break;
        }
    }

    @Override
    public void onQueryStart() {

    }

    @Override
    public void onQueryCanceled() {

    }

    @Override
    public void onQueryResultGened(List<Record> records, boolean hasNextPage) {
        mAdapter.setItems(records);
        if (StringUtils.isNotEmpty(edSearch.getText().toString()))
            tvNoResult.setVisibility(records == null || records.size() == 0 ? View.VISIBLE : View.GONE);
        else
            tvNoResult.setVisibility(View.GONE);
    }

    @Override
    public void onQueryFinish() {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        CustomSearchRecord customSearchRecord = (CustomSearchRecord) mAdapter.getItem(position - mListView.getHeaderViewsCount());
//        CustomArchivesActivity.launch(this, customSearchRecord.custom);
        CompanySearchRecord record = (CompanySearchRecord) mAdapter.getItem(position - mListView.getHeaderViewsCount());
        mCompany = record.company;
        if (selectType == SetCompanyActivity.TYPE_UPLOAD_COMPANY) {
            setCompany();
        } else {
            returnResult();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCustomerListChangeEvent(CustomerListChangeEvent event) {
        searchProxy.query(edSearch.getText().toString().trim());
    }

    @Override
    public void onResume() {
        super.onResume();
//        getActivity().setTitle("搜索公司");
        ((ToolBarCommonActivity) getActivity()).hideToolBar();
        showKeyboard();
    }

    private void showKeyboard() {
        edSearch.requestFocus();
        InputMethodManager mgr = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        mgr.showSoftInput(edSearch, InputMethodManager.SHOW_IMPLICIT);
    }

    public void setCompany() {

    }

    public static CompanySearchFragment newInstance(List<Company> l, int type) {
        CompanySearchFragment f = new CompanySearchFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(SetCompanyActivity.TYPE_KEY, type);
        f.setArguments(bundle);
        f.mListCompany = l;
        return f;
    }

    private void returnResult() {
        Intent i = getActivity().getIntent();
        i.putExtra(BundleKey.PARAM_COMPANY, mCompany);
        getActivity().setResult(Activity.RESULT_OK, i);
        getActivity().finish();
    }

    @Override
    public void onPause() {
        super.onPause();
        AndroidUtils.hideSoftKeyBoard(getActivity(), edSearch);
        ((ToolBarCommonActivity) getActivity()).showToolBar();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadProfileEvent(UploadProfileEvent event) {

    }
}
